package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {

        //1.将页面提交的密码password进行加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

        //2.根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername,employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.没有查询到结果就返回登陆失败
        if(emp == null){
            return R.error("用户名不存在");
        }

        //4.密码比对,不一致返回登陆失败
        if(!emp.getPassword().equals(password)){
            return R.error("密码输入错误");
        }

        //5.查看员工日志如果员工状态是禁用就返回员工账号已经被禁用
        if(emp.getStatus() == 0){
            return R.error("员工账号已经被禁用");
        }

        //6.登录成功,将员工id存到session域并且返回登陆成功
        request.getSession().setAttribute("employee",emp.getId());
        return R.success(emp);
    }

    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request){
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 新增员工
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工信息:{}",employee.toString());

        //初始密码123456,进行加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        //设置创建时间和新增时间和新增人
        //employee.setCreateTime(LocalDateTime.now());
        //employee.setUpdateTime(LocalDateTime.now());
        //employee.setCreateUser((Long) request.getSession().getAttribute("employee"));
        //employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));

        //调用service方法将用户信息添加到数据库
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页查询
     * @param
     * @return
     */
    @GetMapping("/page")
    public R selectByPage(Integer page,
                          Integer pageSize,
                          String name){
        log.info("page={},pageSize={},name = {}",page,pageSize,name);
        //分页构造器
        Page pageInfo = new Page(page,pageSize);

        //条件构造器
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.like(StringUtils.isNotEmpty(name),Employee::getName,name);
        qw.orderByDesc(Employee::getUpdateTime);

        //调用service查询
        employeeService.page(pageInfo,qw);

        List records = pageInfo.getRecords();
        long total = pageInfo.getTotal();

        Map map = new HashMap();
        map.put("total",total);
        map.put("records",records);
        return R.success(map);
    }

    /**
     * 员工的启用禁用
     * @param employee
     * @return
     */
    @PutMapping
    public R updateStatus(HttpServletRequest request,@RequestBody Employee employee){
        log.info(employee.toString());
        //1、修改员工数据的更新时间
        //employee.setUpdateTime(LocalDateTime.now());

        //2、修改员工数据的更新人
        //employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));

        //3、调用业务层修改员工信息
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 编辑员工
     * @param id
     * @return
     */
    @GetMapping ("/{id}")
    public R selectEmployeeById(@PathVariable Long id){
        LambdaQueryWrapper<Employee> qw = new LambdaQueryWrapper<>();
        qw.eq(Employee::getId,id);
        Employee employee = employeeService.getOne(qw);
        return R.success(employee);
    }

}
